package com.tpc.client.systeme.core.datasource;

import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.core.client.GWT;
import com.smartgwt.client.data.Criteria;
import com.smartgwt.client.rpc.RPCResponse;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.tpc.client.systeme.core.Systeme;
import com.tpc.dao.core.Zipcode;
import com.tpc.client.systeme.core.service.AddressService;
import com.tpc.client.systeme.core.service.AddressServiceAsync;
import com.tpc.client.systeme.xtend.datasource.ZipcodeDSFields;

public class ZipCodeDataSource extends GwtRpcDataSource {

    Systeme SYSTEME = null;
    ZipcodeDSFields ZIPFIELDS = new ZipcodeDSFields();

    public ZipCodeDataSource(String strID,Systeme SYSp) {
            setID(strID);
            SYSTEME = SYSp;
            setFields(ZIPFIELDS.setFields());
    }

    @Override
    protected void executeFetch (final String requestId, final DSRequest request, final DSResponse response) {
       Criteria criteria = request.getCriteria();
       String strZipcode = null;
       String strZipcodeCountry = null;
       if (criteria != null) {
           if (criteria.getAttributeAsString("zipcodeTerm") != null) {
               strZipcode = criteria.getAttributeAsString("zipcodeTerm");
           }
           if (criteria.getAttributeAsString("zipcodecountryTerm") != null) {
               strZipcodeCountry = criteria.getAttributeAsString("zipcodecountryTerm");
           }
       }
        AddressServiceAsync service = GWT.create(AddressService.class);
        ServiceDefTarget endpoint = (ServiceDefTarget) service;
        endpoint.setServiceEntryPoint(SYSTEME.getPageUrl()+"/com.tpc.address/addloader");
        service.loadListZipcode(strZipcode,strZipcodeCountry,new AsyncCallback<Zipcode[]> () {
            public void onFailure (Throwable caught) {
                response.setStatus (RPCResponse.STATUS_FAILURE);
                processResponse (requestId, response);
                SYSTEME.stopLoading();
                SYSTEME.handleServerException(caught);
            }
            public void onSuccess (Zipcode[] result) {
                ListGridRecord[] list = ZIPFIELDS.setLGRecord(result);
                response.setData(list);
                processResponse(requestId, response);
            }
        });
    }

    @Override
    protected void executeAdd (final String requestId, final DSRequest request, final DSResponse response) {
        //@TODO : fdsa
    }

    @Override
    protected void executeUpdate (final String requestId, final DSRequest request, final DSResponse response) {
         //@TODO : fdsa
    }

    @Override
    protected void executeRemove (final String requestId, final DSRequest request, final DSResponse response) {
         //@TODO : fdsa
    }
    
}
